package com.th.system.listen;

import com.alibaba.fastjson.JSON;
import com.th.aip.service.AipService;
import com.th.common.constant.AuthConstants;
import com.th.system.domain.UsQuaVerify;
import com.th.system.service.ISysQuaVerifyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ErrorRua
 * @date 2023/06/24
 * @description:
 */

@Component
@Slf4j
public class UserAuthListener {

    @Autowired
    private ISysQuaVerifyService iSysQuaVerifyService;

    @Autowired
    private AipService aipService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(queues = AuthConstants.AUTH_IDENTIFY_QUEUE)
    public void authHandler(String id){
        log.info("接收到用户认证消息===> " + id);

        UsQuaVerify quaVerify = iSysQuaVerifyService.getById(id);
        String examineJson = quaVerify.getExamineJson();
        log.info("认证信息===> " + examineJson);


        Map map = JSON.parseObject(examineJson, Map.class);
        // 1. 获取身份证号
        String idNumber = (String) map.get("idNumber");
        // 2. 获取身份证（国徽面）
        String idCardNationalEmblem = (String) map.get("idPhoto0");
        // 3. 获取身份证（人像面）
        String idCardPortrait = (String) map.get("idPhoto1");
        // 4. 获取姓名
        String name = (String) map.get("name");

        HashMap<String, String> resultMap = aipService.identifyIdcard(idCardPortrait, idCardNationalEmblem, idNumber, name);

        if ("0".equals(resultMap.get("result"))) {
            quaVerify.setExamineResultStatus(1);
        } else {
            quaVerify.setExamineResultStatus(3);
            quaVerify.setExamineResultMessage(resultMap.get("message"));
            quaVerify.setExamineTime(LocalDateTime.now());

            // 发送站内消息
            rabbitTemplate.convertAndSend(AuthConstants.AUTH_EXCHANGE, AuthConstants.AUTH_INTERNAL_MESSAGE_KEY, id);

        }

        iSysQuaVerifyService.updateById(quaVerify);
    }
}
